package com.example.study.page.service

import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.os.RemoteException
import android.widget.Toast
import com.example.study.ListActivity
import com.example.study.R

/**
 * Created by lijinxi on 2024/5/22.
 * @Description:
 */
class MessengerService : Service() {
    companion object {
        const val MSG_REGISTER_CLIENT = 1
        const val MSG_UNREGISTER_CLIENT = 2
        const val MSG_SET_VALUE = 3

        const val CHANNEL_ID = "Messenger Service"
        const val NOTIFICATION_ID = 110
    }

    private lateinit var mNM: NotificationManager

    private val mClients = mutableListOf<Messenger>()

    private var mValue = 0

    override fun onBind(intent: Intent?): IBinder? {
        return mMessenger.binder
    }

    inner class IncomingHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MSG_REGISTER_CLIENT -> {
                    mClients.add(msg.replyTo)
                }

                MSG_UNREGISTER_CLIENT -> {
                    mClients.remove(msg.replyTo)
                }

                MSG_SET_VALUE -> {
                    mValue = msg.arg1
                    for (client in mClients) {
                        try {
                            client.send(Message.obtain(null, MSG_SET_VALUE, mValue, 0))
                        } catch (e: RemoteException) {
                            mClients.remove(client)
                        }
                    }
                }
            }
        }
    }

    private val mMessenger = Messenger(IncomingHandler(Looper.getMainLooper()))

    override fun onCreate() {
        super.onCreate()
        mNM = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        showNotification()
    }

    override fun onDestroy() {
        super.onDestroy()
        mNM.cancel(NOTIFICATION_ID)
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show()
    }

    private fun showNotification() {
        val contentIntent = PendingIntent.getActivity(
            this, 0, Intent(this, ListActivity::class.java),
            PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
        )

        val notification = Notification.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.whale)
            .setTicker("click it.")
            .setWhen(System.currentTimeMillis())
            .setContentTitle(resources.getText(R.string.app_name))
            .setContentText("click it")
            .setContentIntent(contentIntent)
            .build()
        mNM.notify(NOTIFICATION_ID, notification)
    }
}